/**
 * 
 */
package com.imonsoft.common.filter;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.filter.OncePerRequestFilter;

import com.imonsoft.common.constant.CCommon;
import com.imonsoft.common.util.AjaxUtil;
import com.imonsoft.common.util.RequestUtil;

/**
 * 强制安全验证过滤器。验证所请求的url是否在用户的权限范围内。
 * 
 * @author LiQianHui
 * @date 2013-04-17
 * @version 2013
 */
public class SecurityEnforcementFilter extends OncePerRequestFilter {

	@Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
		HttpSession session = request.getSession(false);
		Boolean isLogin = session != null && session.getAttribute(CCommon.USER_INFO) != null;
		String path = request.getContextPath();
		String uri = request.getRequestURI();
		request.setAttribute("REQUEST_URI", uri);// 用于JS
		uri = uri.toLowerCase();// !!
		try {
			if (!uri.startsWith(path + "/login") && !uri.endsWith(".js") && !uri.endsWith(".gif") 
					&& !uri.endsWith(".jpg") && !uri.endsWith(".png") && !uri.endsWith(".css") 
					&& !uri.endsWith(".htm") && !uri.endsWith("/index.do") 
					&& !uri.startsWith(path + "/services")
					&& !uri.startsWith(path + "/demo") && !uri.startsWith(path + "/test")) {
				if (isLogin == Boolean.FALSE) {
					if (session != null) {
						session.invalidate();
					}
					/****** 回到登陆页面 *****/
					if (RequestUtil.isAjaxRequest(request)) {// ajax请求
						AjaxUtil.renderJSON(response, "{sessionState:0}");
						return;
					}
					response.reset();
					response.sendRedirect(path + "/index.do"); //
					return;
				}
			}
			filterChain.doFilter(request, response);
		} catch (ServletException sx) {
			logger.error(sx.getMessage());
			throw sx;
		} catch (IOException iox) {
			logger.error(iox.getMessage());
			throw iox;
		}
	}
}
